import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 基础行接口
export interface BaseTableRow {
  index: number
  [key: string]: any
}

// 表格操作Hook
export function useTableOperations<T extends BaseTableRow>(initialRow: T) {
  // 使用 reactive 替代 ref 来处理数组
  const rows = reactive<T[]>([]) as T[]

  // 添加行
  const addRow = () => {
    const newRow = { 
      ...initialRow, 
      index: rows.length + 1 
    }
    rows.push(newRow)
  }

  // 删除行
  const removeRow = (index: number) => {
    if (rows.length <= 1) {
      ElMessage.warning('至少保留一行数据')
      return
    }
    rows.splice(index, 1)
    reindexRows()
  }

  // 清空所有行
  const clearRows = async (message = '确定要清空所有数据吗？') => {
    try {
      await ElMessageBox.confirm(message, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // 清空数组并添加初始行
      rows.splice(0, rows.length)
      const newRow = { ...initialRow, index: 1 }
      rows.push(newRow)
    } catch {
      ElMessage.info('已取消清空操作')
    }
  }

  // 重新编号
  const reindexRows = () => {
    rows.forEach((row, idx) => {
      row.index = idx + 1
    })
  }

  return {
    rows,
    addRow,
    removeRow,
    clearRows,
    reindexRows
  }
}